from PyQt5.QtWidgets import (
    QVBoxLayout,
    QLabel,
    QHBoxLayout,
    QPushButton,
    QDialog,
    QGridLayout,
)
from PyQt5.QtCore import Qt, Signal
from PyQt5.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage
import sys
import os
import json
import subprocess
import copy
from .custom_widget import LineEditFloat, LineEditStr, LineEditInt, SelectBox
import gui.controls.envs as envs
from . import message_box as MBox


class CGridLayout(QGridLayout):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAlignment(Qt.AlignTop)


class DlgParams(QDialog):
    save_signal = Signal(object)
    alert_signal = Signal(object)

    def __init__(
        self, parent, type="add", data=[], initData=[], lastId=-1, other={}, title=""
    ):
        super().__init__(parent=parent)
        self.data = data
        self.initData = initData
        self.type = type
        self.other = other
        self.lastId = lastId
        self.title = title

        # self.resize(300, 200)
        self.setMinimumWidth(300)
        self.setMinimumHeight(200)
        self.layout = QVBoxLayout(self)
        self.gridLayout = CGridLayout()
        self.widgetDict = {}
        self.createUI(self.gridLayout)
        # self.layout.addStretch()
        self.layout.addLayout(self.gridLayout)
        btnLayout = QHBoxLayout()
        btnLayout.setContentsMargins(10, 15, 10, 0)  # 左, 上, 右, 下
        btnLayout.setAlignment(Qt.AlignCenter)
        if type == "add":
            self.setWindowTitle("添加数据")
        else:
            self.setWindowTitle("修改数据")
        addBtn = QPushButton("确认")
        cancelBtn = QPushButton("取消")
        btnLayout.addWidget(addBtn)
        btnLayout.addWidget(cancelBtn)
        self.layout.addLayout(btnLayout)
        addBtn.setFocusPolicy(Qt.NoFocus)
        cancelBtn.setFocusPolicy(Qt.NoFocus)

        addBtn.clicked.connect(self.on_addBtn_clicked)
        cancelBtn.clicked.connect(self.reject)
        self.setLayout(self.layout)

    def on_addBtn_clicked(self):
        list = []
        for k, v in self.widgetDict.items():
            if v.getRequire() and not v.getValue():
                MBox.warning(f"请输入{v.getLable()}！")
                return
            if "existName" in self.other:
                for name in self.other.get("existName"):
                    if k == "name" and v.getValue() == name:
                        MBox.warning("该名称已存在！")
                        return
            # if v.getValue() == None or v.getValue() == "":
            #     MBox.warning("请将数据补充完整！")
            #     return
            list.append(v.getValue())
        if self.type == "add":
            self.save_signal.emit(list)
        else:
            self.alert_signal.emit(list)

        self.close()

    def createUI(self, gridLayout):
        values = {}
        for row, item in enumerate(self.data):
            if len(self.initData) > 0:
                values[item.get("name")] = self.initData[row]
            label = QLabel(item.get("title"))
            gridLayout.addWidget(label, row, 0)
            if item.get("type") == "str":
                self.widgetDict[item.get("name")] = LineEditStr(data=item)
            elif item.get("type") == "float":
                self.widgetDict[item.get("name")] = LineEditFloat(data=item)
            elif item.get("type") == "int":
                self.widgetDict[item.get("name")] = LineEditInt(data=item)
            elif item.get("type") == "select":
                self.widgetDict[item["name"]] = SelectBox(options=item["options"])
            gridLayout.addWidget(self.widgetDict[item.get("name")], row, 1)

            # if item.get("title") == "id":
            #     label.setVisible(False)
            #     self.widgetDict[item.get("name")].setVisible(False)
            #     if self.lastId >= 0:
            #         self.widgetDict[item.get("name")].setValue(self.lastId + 1)
        if self.type == "add" and self.title:
            self.widgetDict["name"].setText(self.title + "_" + str(self.lastId))

        if len(self.initData) > 0:
            self.updateUI(values)

    def updateUI(self, values):
        for k, v in values.items():
            if k in self.widgetDict:
                self.widgetDict[k].setValue(v)
